package app.android.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.provider.ContactsContract;
import android.util.Log;
import app.android.model.Food;
import app.android.model.History;
import app.android.model.TypeFood;

public class MyDatabaseAdapter {
	private SQLiteDatabase db;
	private final Context context;
	private final MyDatabaseHelper dbhelper;

	public MyDatabaseAdapter(Context context) {
		this.context = context;
		this.dbhelper = new MyDatabaseHelper(context, Constants.DATABASE_NAME,
				null, Constants.DATABASE_VERSION);
	}

	public MyDatabaseHelper getMyDBHelper() {
		return dbhelper;
	}

	public void close() {
		db.close();
	}

	public void open() {
		try {
			db = dbhelper.getWritableDatabase();
		} catch (SQLiteException e) {
			Log.v("Open database exception caught", e.getMessage());
			db = dbhelper.getReadableDatabase();
		}
	}

	/*
	 * private boolean checkDatabaseExists() { 
	 * File database=this.context.getApplicationContext
	 * ().getDatabasePath(Constants.DATABASE_NAME);
	 * 
	 * if (!database.exists()) { // Database does not exist return false; } else
	 * { return true; } }
	 */

	public long addFood(Food food) {
		open();
		ContentValues initialValues = new ContentValues();
		initialValues.put(Constants.FOOD_NAME, food.getFoodName());
		initialValues.put(Constants.FOOD_TYPEID, food.getTypeID());
		initialValues.put(Constants.FOOD_IMAGE_PATH, food.getImagePath());
		initialValues.put(Constants.FOOD_DESCRIPTION, food.getDescription());
		initialValues.put(Constants.FOOD_FAVOURITE, false);

		close();
		return db.insert(Constants.FOOD_TABLE_NAME, null, initialValues);
	}

	public Cursor getAllFoods() {
		open();
		Cursor cursor = db.query(Constants.FOOD_TABLE_NAME, null, null, null,
				null, null, null);
		close();		
		return cursor;
	}
	
	public int getCountFoods() {		
		open();
		Cursor cursor = db.query(Constants.FOOD_TABLE_NAME, null, null, null,
				null, null, null);		
		int result = cursor.getCount();
		close();		
		return result;				
	}
	
	public Food getFoodByID(int ID) {
		open();
		String[] columns = null;
		String where = Constants.KEY_ID + " = " + ID; 
		String[] whereArgs = null;
		Cursor cursor = db.query(Constants.FOOD_TABLE_NAME, null, where, null,
				null, null, null);
		
		Food f = new Food();		
		 // Get the index of the columns.
        int idIdx = cursor.getColumnIndexOrThrow(Constants.KEY_ID);
        int desIdx = cursor.getColumnIndexOrThrow(Constants.FOOD_DESCRIPTION);        
        int favIdx = cursor.getColumnIndexOrThrow(Constants.FOOD_FAVOURITE);
        int imgIdx = cursor.getColumnIndexOrThrow(Constants.FOOD_IMAGE_PATH);
        int nameIdx = cursor.getColumnIndexOrThrow(Constants.FOOD_NAME);
        int typeIdx = cursor.getColumnIndexOrThrow(Constants.FOOD_TYPEID);
                  
        if (cursor.moveToNext()) {
        	f.setID(cursor.getInt(idIdx));
        	f.setDescription(cursor.getString(desIdx));
        	f.setFavourite(cursor.getInt(favIdx));
        	f.setFoodName(cursor.getString(nameIdx));
        	f.setID(cursor.getInt(idIdx));
        	f.setImagePath(cursor.getString(imgIdx));
        	f.setTypeID(cursor.getInt(typeIdx));        	
        }             
        cursor.close();
        close();
        return f;
	}
	
	public boolean changeFavourite(int FoodId, int add) {
		boolean success = false;
		try {
			open();
			ContentValues updateTaskValue = new ContentValues();
			updateTaskValue.put(Constants.FOOD_FAVOURITE,add);
			int i = db.update(Constants.FOOD_TABLE_NAME, updateTaskValue, Constants.KEY_ID +"="+FoodId, null);
			if (i > 0)	success = true;
		}catch (SQLiteException e) {
			Log.v("Update into databse exeption caught",e.getMessage());		
		}
		finally {
			close();
		}
		
		return success;
	}

	public Cursor getAllTypes() {
		open();
		Cursor cursor = db.query(Constants.TYPE_TABLE_NAME, null, null, null,
				null, null, null);
		close();		
		return cursor;
	}
	
	public TypeFood getTypeByID(int ID) {
		open();
		String[] columns = null;
		String where = Constants.KEY_ID + " = " + ID; 
		String[] whereArgs = null;
		Cursor cursor = db.query(Constants.TYPE_TABLE_NAME, columns, where, whereArgs,
				null, null, null);
		
		TypeFood t = new TypeFood();		
		
        int idIdx = cursor.getColumnIndexOrThrow(Constants.KEY_ID);
        int desIdx = cursor.getColumnIndexOrThrow(Constants.TYPE_DESCRIPTION);      
        int nameIdx = cursor.getColumnIndexOrThrow(Constants.TYPE_NAME);
        
        if (cursor.moveToNext()) {
        	t.setID(cursor.getInt(idIdx));
        	t.setDescription(cursor.getString(desIdx)); 
        	t.setTypeName(cursor.getString(nameIdx));        	        	
        }             
        cursor.close();
        close();
        return t;
	}
	
	public Cursor getAllHistories() {
		open();
		Cursor cursor = db.query(Constants.HIS_TABLE_NAME, null, null, null,
				null, null, null);
//		close();		
		return cursor;
	}
	
	public boolean updateHistory(History history) {
		boolean success = false;
		try {
			open();
			ContentValues updateTaskValue = new ContentValues();
			updateTaskValue.put(Constants.HIS_FOOD_ID, history.getHisFoodId());
			updateTaskValue.put(Constants.HIS_TIME, history.getHisTime());
			int i = db.update(Constants.HIS_TABLE_NAME, updateTaskValue, Constants.HIS_FOOD_ID +"="+history.getHisFoodId(), null);
			if (i > 0)	success = true;
		}catch (SQLiteException e) {
			Log.v("Update into databse exeption caught",e.getMessage());		
		}
		finally {
			close();
		}
		
		return success;
	}
	
	public void deleteAllHistory() {
		try {
			open();
			db.delete(Constants.HIS_TABLE_NAME, null, null);		
		}catch (SQLiteException e) {
			Log.v("Delete into databse exeption caught",e.getMessage());		
		}
		finally {
			close();
		}			
	}
	
	public void deleteOldHistory() {
		try {
			open();
			String where = "monAnID NOT IN (SELECT monAnID FROM lich_su ORDER BY thoiGian desc LIMIT 0,20)";
			db.delete(Constants.HIS_TABLE_NAME, where, null);		
		}catch (SQLiteException e) {
			Log.v("Delete into databse exeption caught",e.getMessage());		
		}
		finally {
			close();
		}			
	}
	
	public boolean addHistory(History history) {
		boolean success = false;
		try {
			open();
			ContentValues initialValues = new ContentValues();
			initialValues.put(Constants.HIS_FOOD_ID, history.getHisFoodId());
			initialValues.put(Constants.HIS_TIME, history.getHisTime());		
			long i = db.insert(Constants.HIS_TABLE_NAME, null, initialValues);
			if (i > 0)	success = true;
		}catch (SQLiteException e) {
			Log.v("Update into databse exeption caught",e.getMessage());		
		}
		finally {
			close();
		}
		
		return success;
	}
	
	public History getHistoryByFoodID(int foodID) {
		open();
		String[] columns = null;
		String where = Constants.HIS_FOOD_ID + " = " + foodID; 
		String[] whereArgs = null;
		Cursor cursor = db.query(Constants.HIS_TABLE_NAME, columns, where, whereArgs,
				null, null, null);
		
		History h = new History();		
		
        int foodIdx = cursor.getColumnIndexOrThrow(Constants.HIS_FOOD_ID);
        int timeIdx = cursor.getColumnIndexOrThrow(Constants.HIS_TIME);      
        
        
        if (cursor.moveToNext()) {
        	h.setHisFoodId(cursor.getInt(foodIdx));
        	h.setHisTime(cursor.getString(timeIdx));        	        	        	
        }             
        cursor.close();
        close();
        return h;
	}
	
}
